//  Android Carpool System
//  2011-2011
//  Author: Jinhuan Wang
//  name: ServletApp.java
//  description: provide service for front end app 
//$history: /carpoolservice/scr/com/carpool/service/ServletApp.java$
/*************************************************/
// add    credit requirement remainder attributions and change CEndPoint 
// and CStartPoint into CStartPoints and CEndPoints
// move xml to object and object to xml into carpoolservice.scr.com.dataexchange.Convert.java
// Author: Jinhuan Wang Date 2011-5-19
/*************************************************/

package com.carpool.service;

import java.io.DataOutputStream;
import java.io.IOException;
import java.sql.SQLException;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.dataexchange.Convert;
import com.dataexchange.ReplyMessage;
import com.dataexchange.State;
import com.dataexchange.postData;
import com.dataexchange.s2dReply;

@SuppressWarnings("serial")
public class ServletApp extends HttpServlet {
	public void doGet(HttpServletRequest request, HttpServletResponse response)
			throws IOException, ServletException {
		// System.out.println("@@@@@@");
		response.setContentType("text/xml");
		ReplyMessage rpl = null;
		postData mRequest = Convert.parseRequest(request);
		if (mRequest != null) {
			try {
				rpl = reply(mRequest, response);
			} catch (SQLException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			if (rpl != null) {
				sendback(rpl, response);
			}
		}

	}

	private void sendback(ReplyMessage rpl, HttpServletResponse response) {
		// TODO Auto-generated method stub
		StringBuffer sb = Convert.genXML(rpl);
		DataOutputStream dos;
		try {
			dos = new DataOutputStream(response.getOutputStream());
			byte[] xmlbyte;
			xmlbyte = sb.toString().getBytes("UTF-8");
			dos.write(xmlbyte);
			dos.close();
		} catch (Exception e) {
			e.printStackTrace();
		}

	}
		

	public void doPost(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		doGet(request, response);
	}

	private ReplyMessage reply(postData mRequest, HttpServletResponse response)
			throws SQLException {
		DBOperation DBO = new DBOperation();
		ReplyMessage rpl = null;
		if (mRequest.getPostType() == true) // Pdata
		{
			rpl = DBO.queryRoute(mRequest);
			return rpl;
		} else// Ddata
		{
			s2dReply rplImpl =new s2dReply();
			if(DBO.insertRoute(mRequest)!=0)
				rplImpl.setState(State.success);
			return rplImpl;
		}
	}

	public void destroy() {
	}

	

}
